package com.googlecode.protoserv;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;

import com.google.protobuf.ByteString;

class ByteStream extends ByteArrayOutputStream {

  public ByteStream(int capacity) {
    super(capacity);
  }

  public ByteStream() {
    this(128);
  }

  public void encsureCapacity(int size) {
    if (size > this.buf.length) {
      byte[] buffer = new byte[size];
      System.arraycopy(this.buf, 0, buffer, 0, this.count);
      this.buf = buffer;
    }
  }

  public InputStream asInput() {
    return new ByteArrayInputStream(this.buf, 0, this.count);
  }

  public ByteString toByteString() {
    return ByteString.copyFrom(this.buf, 0, this.count);
  }

  public void write(ByteString bytes) throws IOException {
    WritableByteChannel channel = Channels.newChannel(this);
    channel.write(bytes.asReadOnlyByteBuffer());
  }
}

